package com.xykj.deploy.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.databind.util.JSONPObject;
import lombok.Data;

import java.io.Serial;
import java.io.Serializable;

/**
 * @author Ethan
 * createTime 2024/06/25 09:04
 * description
 * version 1.0
 */
@Data
public class Result<T> implements Serializable {

    @Serial
    private static final long serialVersionUID = 5961871655750037183L;

    /**
     * 返回处理消息
     */
    private String msg = "";

    /**
     * 返回代码
     */
    private Integer code = 0;
    /**
     * 返回数据对象 data
     */
    private T data;

    /**
     * 返回失败消息
     */
    public static <T> Result<T> error(String msg) {
        Result<T> r = new Result<T>();
        r.setCode(500);
        r.setMsg(msg);
        return r;
    }

    /**
     * 返回成功消息
     */
    public static <T> Result<T> ok(String msg) {
        Result<T> r = new Result<T>();
        r.setCode(0);
        r.setMsg(msg);
        return r;
    }

    /**
     * 返回成功消息
     */
    public static <T> Result<T> ok(T data) {
        Result<T> r = new Result<T>();
        r.setCode(0);
        r.setMsg("请求成功");
        r.setData(data);
        return r;
    }

    /**
     * 返回成功消息
     */
    public static <T> Result<T> ok(String msg, T data) {
        Result<T> r = new Result<T>();
        r.setCode(0);
        r.setMsg(msg);
        r.setData(data);
        return r;
    }

    /**
     * 返回成功消息
     */
    public static Result<Object> ok(ObjectNode dataObj) {
        Result<Object> r = new Result<Object>();
        r.setCode(dataObj.get("code").asInt());
        r.setMsg(dataObj.get("msg").asText());
        r.setData(dataObj.get("data"));
        return r;
    }

    /**
     * Convert Result to JSON string
     */
    public String toJsonString() {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            return objectMapper.writeValueAsString(this);
        } catch (Exception e) {
            throw new RuntimeException("Error converting Result to JSON", e);
        }
    }

    /**
     * Create Result from JSON string
     */
    public static <T> Result<T> fromJsonString(String json, Class<T> dataClass) {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            return objectMapper.readValue(json, objectMapper.getTypeFactory().constructParametricType(Result.class, dataClass));
        } catch (Exception e) {
            throw new RuntimeException("Error creating Result from JSON", e);
        }
    }
}
